package org.promote.hotspot.dashboard.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.StringUtils;
import org.promote.hotspot.common.model.HotKeyModel;
import org.promote.hotspot.common.model.HotSpotMsg;
import org.promote.hotspot.common.model.MessageType;
import org.promote.hotspot.common.model.MsgBuilder;
import org.promote.hotspot.common.tool.FastJsonUtils;
import org.promote.hotspot.dashboard.tool.FlushUtil;

import java.util.List;

import static org.promote.hotspot.common.tool.Constant.PONG;

/**
 * @author enping.jep
 * @date 2024/02/21 16:16
 **/
public class DashboardServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) {
        if (StringUtils.isEmpty(message)) {
            return;
        }
        try {
            HotSpotMsg msg = FastJsonUtils.toBean(message, HotSpotMsg.class);
            if (MessageType.PING == msg.getMessageType()) {
                String hotMsg = FastJsonUtils.convertObjectToJSON(new HotSpotMsg(MessageType.PONG, PONG));
                FlushUtil.flush(ctx, MsgBuilder.buildByteBuf(hotMsg));
            } else if (MessageType.REQUEST_HOT_KEY == msg.getMessageType()) {
                List<HotKeyModel> list = FastJsonUtils.toList(msg.getBody(), HotKeyModel.class);
                for (HotKeyModel hotKeyModel : list) {
                    HotSpotReceiver.push(hotKeyModel);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
